<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" :default-params="{ adCode: [] }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="commissionConfigListCRUD.page"
      column-controller-key="commissionConfigList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['system:commission-config:create']"
            @click="handleOpenDialog('create', { defaultConfig: '0', adCode: [] })"
          >
            新建配置
          </t-button>
        </div>
      </template>
      <template #defaultConfig="{ row }">
        <t-switch
          v-model:value="row.defaultConfig"
          :custom-value="['1', '0']"
          :loading="row.loading"
          @change="handleChangeDefaultConfig(row)"
        />
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:commission-config:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:commission-config:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:commission-config:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="commissionConfigListCRUD"
      header="*配置"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="默认配置" name="defaultConfig" :rules="[{ required: true, message: '请选择默认配置' }]">
        <t-switch v-model:value="formData.defaultConfig" :custom-value="['1', '0']" :disabled="readonly" />
      </t-form-item>
      <t-form-item
        v-if="formData.defaultConfig === '0'"
        label="归属城市"
        name="adCode"
        :rules="[{ required: true, message: '请选择归属城市' }]"
      >
        <t-cascader
          v-model:value="formData.adCode"
          :options="city.tree"
          :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
          placeholder="请选择归属城市"
          filterable
          clearable
          :readonly="readonly"
          value-type="full"
          @change="(value: any) => handleAdCodeChange(value, formData)"
        />
      </t-form-item>
      <t-form-item label="有效金额" name="effectiveMoney" :rules="[{ required: true, message: '请输入有效金额' }]">
        <t-input-number
          v-model:value="formData.effectiveMoney"
          placeholder="请输入有效金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="有效积分" name="effectivePoints" :rules="[{ required: true, message: '请输入有效积分' }]">
        <t-input-number
          v-model:value="formData.effectivePoints"
          placeholder="请输入有效积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="量房金额" name="measureMoney" :rules="[{ required: true, message: '请输入量房金额' }]">
        <t-input-number
          v-model:value="formData.measureMoney"
          placeholder="请输入量房金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="量房积分" name="measurePoints" :rules="[{ required: true, message: '请输入量房积分' }]">
        <t-input-number
          v-model:value="formData.measurePoints"
          placeholder="请输入量房积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="签约金额" name="signMoney" :rules="[{ required: true, message: '请输入签约金额' }]">
        <t-input-number
          v-model:value="formData.signMoney"
          placeholder="请输入签约金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="签约积分" name="signPoints" :rules="[{ required: true, message: '请输入签约积分' }]">
        <t-input-number
          v-model:value="formData.signPoints"
          placeholder="请输入签约积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级有效金额"
        name="parentEffectiveMoney"
        :rules="[{ required: true, message: '请输入上级有效金额' }]"
      >
        <t-input-number
          v-model:value="formData.parentEffectiveMoney"
          placeholder="请输入上级有效金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级有效积分"
        name="parentEffectivePoints"
        :rules="[{ required: true, message: '请输入上级有效积分' }]"
      >
        <t-input-number
          v-model:value="formData.parentEffectivePoints"
          placeholder="请输入上级有效积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级量房金额"
        name="parentMeasureMoney"
        :rules="[{ required: true, message: '请输入上级量房金额' }]"
      >
        <t-input-number
          v-model:value="formData.parentMeasureMoney"
          placeholder="请输入上级量房金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级量房积分"
        name="parentMeasurePoints"
        :rules="[{ required: true, message: '请输入上级量房积分' }]"
      >
        <t-input-number
          v-model:value="formData.parentMeasurePoints"
          placeholder="请输入上级量房积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级签约金额"
        name="parentSignMoney"
        :rules="[{ required: true, message: '请输入上级签约金额' }]"
      >
        <t-input-number
          v-model:value="formData.parentSignMoney"
          placeholder="请输入上级签约金额"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item
        label="上级签约积分"
        name="parentSignPoints"
        :rules="[{ required: true, message: '请输入上级签约积分' }]"
      >
        <t-input-number
          v-model:value="formData.parentSignPoints"
          placeholder="请输入上级签约积分"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'CommissionConfig',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, onUpdated, useTemplateRef } from 'vue';

import { commissionConfigListCRUD } from '@/api/distribution/commission-config';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import city from '@/utils/city';

// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '配置ID' },
  { colKey: 'defaultConfig', title: '默认配置', width: 100 },
  { colKey: 'adCode', title: '归属城市', width: 250 },
  { colKey: 'effectiveMoney', title: '有效金额', width: 100 },
  { colKey: 'effectivePoints', title: '案例风格', width: 100 },
  { colKey: 'measureMoney', title: '量房金额', width: 100 },
  { colKey: 'measurePoints', title: '量房积分', width: 100 },
  { colKey: 'signMoney', title: '签约金额', width: 100 },
  { colKey: 'signPoints', title: '签约积分', width: 100 },
  { colKey: 'parentEffectiveMoney', title: '上级有效金额', width: 120 },
  { colKey: 'parentEffectivePoints', title: '上级有效积分', width: 120 },
  { colKey: 'parentMeasureMoney', title: '上级量房金额', width: 120 },
  { colKey: 'parentMeasurePoints', title: '上级量房积分', width: 120 },
  { colKey: 'parentSignMoney', title: '上级签约金额', width: 120 },
  { colKey: 'parentSignPoints', title: '上级签约积分', width: 120 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  if (!params.adCode.length) {
    delete params.province;
    delete params.city;
    delete params.area;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  params.adCode = [];
  if (params.province) params.adCode.push(params.province);
  if (params.city) params.adCode.push(params.city);
  if (params.area) params.adCode.push(params.area);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  commissionConfigListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.province = value[0] || '';
  params.city = value[1] || '';
  params.area = value[2] || '';
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
// 处理改变默认配置
const handleChangeDefaultConfig = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  commissionConfigListCRUD
    .update(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
      handleRefreshTable();
    });
};
</script>

<style lang="less" scoped></style>
